package com.qf.air.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * JSON处理工具类
 * @author zjw
 */
public class JSONUtil {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将Object对象序列化为JSON字符串
     * @param obj
     * @return
     */
    public static String obj2JSON(Object obj){
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T json2Obj(String json,Class<T> clazz){
        T t = null;
        try {
            t = OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }


    public static List<Map> jsonArray2ListMap(String json){
        List<Map> data = null;
        try {
            data = OBJECT_MAPPER.readValue(json, new TypeReference<List<Map>>(){});
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }


}
